import { defineStore } from 'pinia'
import type { CaseState } from '../type'
import type { ICaseProcessItem, processStatusType } from '@/views/cases/type'

const useCasesStore = defineStore({
  id: 'cases',
  state: (): CaseState => ({
    caseProcess: [],
    caseInfo: null,
    formInfo: null,
    caseResult: null,
    caseRunLoading: false,
    processUpdate: {
      'Caculation Result': false,
      'SOM': false,
      'Sensitivity analysis': false,
      'Optimization': false,
      'Contribution': false,
    },
    currentStepNumber: 0,
    wsNotifyEndStatus: false,
    clusterMax: 1,
  }),
  actions: {
    setClusterMax(number: number) {
      this.clusterMax = number
    },
    setCaseProcess(data: ICaseProcessItem[]) {
      this.caseProcess = data
    },
    setCurrentStepNumber(step: number) {
      this.currentStepNumber = step
    },
    setWsNotifyEndStatus(status: boolean) {
      this.wsNotifyEndStatus = status
    },
    setCaseProcessUpdate(data?: Record<string, boolean>) {
      if (!data) {
        this.processUpdate = {
          'Caculation Result': true,
          'SOM': true,
          'Sensitivity analysis': true,
          'Optimization': true,
          'Contribution': true,
        }
        return
      }
      const updateProcess = Object.assign({}, this.processUpdate, data)
      this.processUpdate = updateProcess
    },
    updateCaseProcess(finishSteps: any[], status: processStatusType = 'finish') {
      const updateProcess = this.caseProcess.map((item: any) => {
        const newItem = { ...item }
        if (finishSteps.includes(newItem.title))
          newItem.status = status

        return newItem
      })
      this.caseProcess = updateProcess
    },
    initFormInfoSkip() {
      const defaultNoSkipSteps = ['Clean', 'Sampling', 'Normalization', 'DR', 'Cluster']
      const formInfo = Object.fromEntries(Object.entries(this.formInfo as any).map(([key, value]) => {
        if (typeof value === 'object') {
          if (defaultNoSkipSteps.includes(key))
            return [key, { ...value, skip: false }]
          else
            return [key, { ...value, skip: true }]
        }
        else {
          return [key, value]
        }
      }))
      this.formInfo = formInfo
    },
    setCaseInfo(data: any) {
      this.caseInfo = data
    },
    saveFormInfo(data: any) {
      this.formInfo = data
    },
    setCaseResult(data: any) {
      this.caseResult = data
    },
    setCaseRunLoading(loading: boolean) {
      this.caseRunLoading = loading
    },
    async RESET_STATE() {
      this.$reset()
    },
  },
})

export default useCasesStore
